package com.leyou.order.interceptors;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    private final static String COOKIE_NAME = "LY_TOKEN";

    /**
     *  把用户信息存入ThreadLocal中
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            //获取token
            String token = CookieUtils.getCookieValue(request, COOKIE_NAME);
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
            //获取用户信息
            UserInfo userInfo = payload.getUserInfo();
            //存入ThreadLocal
            UserHolder.setUser(userInfo);
            return true;
        } catch (UnsupportedEncodingException e) {
            log.error("【购物车微服务】解析用户信息异常 {}",e.getMessage());
            return false;
        }
    }

    /**
     *  线程结束把存进入的用户信息给删除了
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
